package com.jsjosem.aftersales.ui.notifications;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.jsjosem.aftersales.R;
import com.jsjosem.aftersales.adapter.WorkNotifyAdapter;
import com.jsjosem.aftersales.api.NotificationsApi;
import com.jsjosem.aftersales.api.RetrofitClient;
import com.jsjosem.aftersales.data.response.BaseResponse;
import com.jsjosem.aftersales.data.response.NotificationsResponse;
import com.jsjosem.aftersales.data.response.PageResponse;
import com.jsjosem.aftersales.request.AsyncRequest;
import com.jsjosem.aftersales.ui.worktickets.WorkTicketsInfoActivity;
import com.jsjosem.aftersales.utils.PageUtils;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Retrofit;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link WorkTicketNotifyListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class WorkTicketNotifyListFragment extends Fragment {

    private static final String TAG = WorkTicketNotifyListFragment.class.getName();

    private Context context;
    private RecyclerView recyclerView;
    private WorkNotifyAdapter workNotifyAdapter;
    private List<NotificationsResponse> notificationsResponses = new ArrayList<>();
    private SmartRefreshLayout smartRefreshLayout;
    private Dialog loadingDialog;
    private final static int INDEX_PAGE = 1;
    private final static int REFRESH = 2;
    private final static int LOAD_MORE = 3;
    private int currentPage = 1;
    private Retrofit mRetrofit;
    private NotificationsApi notificationsApi;

    public WorkTicketNotifyListFragment() {
    }

    public static WorkTicketNotifyListFragment newInstance() {
        return new WorkTicketNotifyListFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_page_list, container, false);
        context = view.getContext();
        initView(view);
        initData();
        smartRefreshLayout.setEnableAutoLoadMore(false);
        loadMore();

        workNotifyAdapter.setOnItemClickListener((v, position) -> {
            NotificationsResponse notificationsResponse = notificationsResponses.get(position);
            // 标记通知已读
            Call<BaseResponse<Void>> markReadCall = notificationsApi.markRead(notificationsResponse.getmId());
            AsyncRequest<BaseResponse<Void>> request = new AsyncRequest<>();
            request.sendRequest(markReadCall, res -> {
                notificationsResponses.get(position).setmStatus(Long.parseLong("1"));
                workNotifyAdapter.notifyItemChanged(position);
                Log.d(TAG, "标记通知已读成功");
            }, errMsg -> Toast.makeText(context, errMsg.toString(), Toast.LENGTH_SHORT).show());
            Long workId = notificationsResponse.getmBusinessId();
            Intent intent = new Intent(getContext(), WorkTicketsInfoActivity.class);
            intent.putExtra("workId", workId);
            startActivity(intent);
        });

        return view;
    }

    private void initView(View view) {
        smartRefreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.ticket_recycler_view);
        mRetrofit = RetrofitClient.getInstance();
        notificationsApi = mRetrofit.create(NotificationsApi.class);
    }

    private void initData() {
        workNotifyAdapter = new WorkNotifyAdapter(context, notificationsResponses);
        recyclerView.setAdapter(workNotifyAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        loadingShow();
        getData(currentPage++);
    }

    private void getData(int currentPage) {
        Call<PageResponse<NotificationsResponse>> events = notificationsApi.getNotificationsByPage("work_order", currentPage, 10);
        AsyncRequest<PageResponse<NotificationsResponse>> request = new AsyncRequest<>();
        request.sendRequest(events, res -> {
            int totalPage = PageUtils.totalPage(10, res.getCount());
            if (currentPage > totalPage) {
                smartRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                notificationsResponses.addAll(res.getData());
                workNotifyAdapter.notifyDataSetChanged();
                loadingDialog.dismiss();
            }
        }, err -> {
        });
    }

    private void loadingShow() {
        loadingDialog = new Dialog(context, R.style.normal_dialog_style);
        View loadingView = View.inflate(context, R.layout.dialog_loading, null);
        loadingDialog.setContentView(loadingView);
        //使得点击对话框外部不消失对话框
        loadingDialog.setCanceledOnTouchOutside(false);
        AVLoadingIndicatorView avi = loadingView.findViewById(R.id.avi);
        avi.show();
        loadingDialog.show();
    }

    private void loadMore() {
        smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            /**
             * 加载更多
             * @param refreshLayout
             */
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                getData(currentPage++);
                smartRefreshLayout.finishLoadMore();
            }

            /**
             * 下拉刷新
             * @param refreshLayout
             */
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                currentPage = 1;
                notificationsResponses.clear();
                getData(currentPage++);
                smartRefreshLayout.finishRefresh();
            }
        });
    }
}